package com.github.ylt.protocol.soap;

import com.github.ylt.utils.SOAPUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.ReferenceCountUtil;

import java.nio.charset.StandardCharsets;

/**
 * @author wutong
 */
public class SOAPHandler extends SimpleChannelInboundHandler<HttpObject> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        DefaultHttpResponse response = null;
        if (msg instanceof FullHttpRequest request) {
           if("/AVTransport/action".equals(request.uri())){
               String s = request.headers().get("SOAPACTION");
               String[] split = s.split("#");
               if("Stop".equals(split[1])){
                   String s1 = SOAPUtils.getInstance().buildBody("", s, split[1]);
                   System.out.println(s1);
                   ByteBuf data = Unpooled.copiedBuffer(s1.getBytes(StandardCharsets.UTF_8));
                   response = new DefaultFullHttpResponse(request.protocolVersion(),HttpResponseStatus.OK,data);
                   response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/xml;charset=utf-8");
                   response.headers().set(HttpHeaderNames.ALLOW,"GET, HEAD, POST, SUBSCRIBE, UNSUBSCRIBE");
                   response.headers().set(HttpHeaderNames.CONTENT_LENGTH,data.readableBytes());
                   response.headers().set(HttpHeaderNames.SERVER,new String("ubuntu/22.04 UPnP/1.0 我是你爹/1.0".getBytes(), StandardCharsets.UTF_8));
                   ctx.writeAndFlush(response);
                   return;
               }
               if ("SetAVTransportURI".equals(split[1])){

               }
           }
        }
    }
}
